using ELportal.Common.Models;
using ELportal.Repositories;

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OutputCaching;

namespace ELportal.App.Controllers;

public class UsersController : BaseController
{
	private readonly IUserRepository userRepository;

	public UsersController(IUserRepository userRepository)
	{
		this.userRepository = userRepository;
	}

	[HttpGet]
	public async Task<IActionResult> Get(CancellationToken cancellationToken = default)
	{
		var users = (await userRepository.GetAsync(cancellationToken))?
			.GroupBy(x => (x as User)?.Department)
			.ToDictionary(x => x.Key ?? string.Empty, x => x);

		return Ok(users);
	}

	[HttpGet("{id:int}")]
	[OutputCache(VaryByQueryKeys = [ "id" ])]
	public async Task<IActionResult> Get(uint id, CancellationToken cancellationToken = default)
	{
		var user = await userRepository.GetAsync(id, cancellationToken);

		if (user == null)
			return NotFound(id);

		return Ok(user);
	}

	[HttpGet("me")]
	public async ValueTask<IActionResult> GetMe(CancellationToken cancellationToken = default)
	{
		var meLogon = User.Identity?.Name?
			.Split('\\', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
			.Last();

		if (string.IsNullOrWhiteSpace(meLogon))
			return NotFound();

		var user = await userRepository.GetAsync(meLogon, cancellationToken);

		return Ok(user);
	}
}
